package com.ysd.lis.service.eq.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.WkFolder;
import com.ysd.lis.entity.eq.*;
import com.ysd.lis.mapper.eq.*;
import com.ysd.lis.request.CommonPageDto;
import com.ysd.lis.request.eq.EqMaintainDto;
import com.ysd.lis.request.eq.EqRepairParam;
import com.ysd.lis.request.eq.MaintainTjfxVo;
import com.ysd.lis.service.SysBasDictDetailService;
import com.ysd.lis.service.SysRuleSetService;
import com.ysd.lis.service.WkFolderService;
import com.ysd.lis.service.eq.EqMaintainDetailService;
import com.ysd.lis.service.eq.EqMaintainOrderService;
import com.ysd.lis.service.eq.EqMaintainPersonService;
import com.ysd.util.ToolsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.YearMonth;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 设备管理-设备类型 服务实现类
 * </p>
 *
 * @author prs
 * @since 2024-07-31
 */
@Service
public class EqMaintainOrderServiceImpl extends ServiceImpl<EqMaintainOrderMapper, EqMaintainOrder> implements EqMaintainOrderService {

    @Autowired
    EqMaintainOrderMapper eqMaintainOrderMapper;
    @Autowired
    EqMaintainPersonService eqMaintainPersonService;
    @Autowired
    EqMaintainDetailService eqMaintainDetailService;
    @Autowired
    SysRuleSetService sysRuleSetService;//编码规则服务
    @Autowired
    EqMaintainPersonMapper eqMaintainPersonMapper;
    @Autowired
    EqMaintainDetailMapper eqMaintainDetailMapper;
    @Override
    public Result findMaintainOrderPageList(CommonPageDto pageParam) {
        Page<EqMaintainOrder> page = new Page<>();
        page.setCurrent(pageParam.getPageIndex());
        page.setSize(pageParam.getPageSize());
        MPJLambdaWrapper<EqMaintainOrder> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(EqMaintainOrder.class)
                .selectAs("eq",EqEquipment::getEquiptName,EqMaintainOrder::getEquiptName)
                .selectAs("eq",EqEquipment::getSpecification,EqMaintainOrder::getSpecification)
                .leftJoin(EqEquipment.class,"eq",EqEquipment::getId,EqMaintainOrder::getEquiptId)
                .eq(EqMaintainOrder::getDelFlag, 0);
        if (StringUtils.isNotBlank(pageParam.getSeachValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(EqMaintainOrder::getMaintainNo, pageParam.getSeachValue())
                    .or().like(EqMaintainOrder::getEquiptCode, pageParam.getSeachValue()));
        }
        if(ToolsUtils.isNotEmpty(pageParam.getStatus())){
            lambdaQueryWrapper.eq(EqMaintainOrder::getMaintainStatus,pageParam.getStatus());
        }
        if(ToolsUtils.isNotEmpty(pageParam.getPlanId())){
            lambdaQueryWrapper.eq(EqMaintainOrder::getPlanId,pageParam.getPlanId());
        }
        if(ToolsUtils.isNotEmpty(pageParam.getEquiptId())){
            lambdaQueryWrapper.eq(EqMaintainOrder::getEquiptId,pageParam.getEquiptId());
        }
        lambdaQueryWrapper.orderByDesc(EqMaintainOrder::getCreateTime);
        Page<EqMaintainOrder> orderPage = eqMaintainOrderMapper.selectPage(page, lambdaQueryWrapper);
        List<EqMaintainOrder> records = orderPage.getRecords();
        for(EqMaintainOrder order : records){
            String maintainStatus = order.getMaintainStatus();
            if(!maintainStatus.equals("15")){
                Timestamp nextDate = order.getPlanDate();
                if(ToolsUtils.isNotEmpty(nextDate)){
                    long diff = Math.abs(new Date().getTime() - nextDate.getTime());
                    order.setOverdue(diff / (1000 * 60 * 60 * 24));
                }

            }
        }
        return Result.succ(1, "查询成功", orderPage);
    }

    @Override
    public Result addMaintainOrder(EqMaintainOrder eqMaintainOrder) {
        String a = sysRuleSetService.createRuleCodeList("eqMaintainNo", 1).get(0);
        eqMaintainOrder.setMaintainNo(a);
        if(ToolsUtils.isNotEmpty(eqMaintainOrder.getPlanId())){
            String repairStatus = eqMaintainOrder.getMaintainStatus();
            if(repairStatus.equals("15")){
                eqMaintainOrder.setMaintainStatus("10");
            }
        }
        boolean save = this.save(eqMaintainOrder);
        if (save) {
            //person
            List<EqMaintainPerson> maintainPersonList = eqMaintainOrder.getMaintainPersonList();
            for(EqMaintainPerson maintainPerson : maintainPersonList){
                maintainPerson.setMaintainId(eqMaintainOrder.getId());
                maintainPerson.setMaintainNo(eqMaintainOrder.getMaintainNo());
            }
            boolean b = eqMaintainPersonService.saveBatch(maintainPersonList);

            //detail
            List<EqMaintainDetail> maintainDetailList = eqMaintainOrder.getMaintainDetailList();
            for(EqMaintainDetail maintainDetail : maintainDetailList){
                maintainDetail.setMaintainId(eqMaintainOrder.getId());
                maintainDetail.setMaintainNo(eqMaintainOrder.getMaintainNo());
            }
            boolean b1 = eqMaintainDetailService.saveBatch(maintainDetailList);
            //创建文件夹
            List<Map<String, Object>> fileFolderList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("eqFileFolder").getData();
            List<WkFolder> sbList = wkFolderService.list(new LambdaQueryWrapper<WkFolder>().eq(WkFolder::getCode, "eqMaintainOrder").eq(WkFolder::getDelFlag, 0));
            if (CollectionUtil.isNotEmpty(sbList)) {
                WkFolder sbFolder = sbList.get(0);
                String[] split = sbFolder.getFileFolder().split(",");
                WkFolder wkFolder = new WkFolder();
                wkFolder.setCode(a);
                wkFolder.setName(a);
                wkFolder.setPid(sbFolder.getId());
                wkFolder.setGrade(0);
                wkFolderService.save(wkFolder);
                if (split.length > 0) {
                    for (String fileFolder : split) {
                        for (Map<String, Object> map : fileFolderList) {
                            if (fileFolder.equals(map.get("code"))) {
                                WkFolder wkFolder1 = new WkFolder();
                                wkFolder1.setCode(a+fileFolder);
                                wkFolder1.setName(map.get("name").toString());
                                wkFolder1.setPid(wkFolder.getId());
                                wkFolder1.setGrade(0);
                                wkFolderService.save(wkFolder1);
                            }
                        }
                    }
                }
            }
            return Result.succ(1, "添加成功", eqMaintainOrder);

        } else {
            return Result.fail("添加失败");
        }
    }
    @Autowired
    WkFolderService wkFolderService;
    @Autowired
    SysBasDictDetailService sysBasDictDetailService;
    @Override
    public Result findEqMaintainOrderById(EqMaintainOrder eqMaintainOrder) {
        String id = eqMaintainOrder.getId();
        //EqMaintainOrder maintainOrder = this.getById(id);

        MPJLambdaWrapper<EqMaintainOrder> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(EqMaintainOrder.class)
                .selectAs("eq",EqEquipment::getEquiptName,EqMaintainOrder::getEquiptName)
                .selectAs("eq",EqEquipment::getSpecification,EqMaintainOrder::getSpecification)
                .leftJoin(EqEquipment.class,"eq",EqEquipment::getId,EqMaintainOrder::getEquiptId)
                .eq(EqMaintainOrder::getId,id)
                .eq(EqMaintainOrder::getDelFlag, 0);
        EqMaintainOrder maintainOrder = eqMaintainOrderMapper.selectOne(lambdaQueryWrapper);

        //获取person
        MPJLambdaWrapper<EqMaintainPerson> queryTableWrapper = new MPJLambdaWrapper<>();
        queryTableWrapper.selectAll(EqMaintainPerson.class)
                .eq(EqMaintainPerson::getMaintainId,id)
                .eq(EqMaintainPerson::getDelFlag,0);
        List<EqMaintainPerson> personList = eqMaintainPersonMapper.selectList(queryTableWrapper);
        maintainOrder.setMaintainPersonList(personList);
        //获取detail

        MPJLambdaWrapper<EqMaintainDetail> queryTableWrapper1 = new MPJLambdaWrapper<>();
        queryTableWrapper1.selectAll(EqMaintainDetail.class)
                .eq(EqMaintainDetail::getMaintainId,id)
                .eq(EqMaintainDetail::getDelFlag,0);
        List<EqMaintainDetail> detailList = eqMaintainDetailMapper.selectList(queryTableWrapper1);
        maintainOrder.setMaintainDetailList(detailList);

        return Result.succ(1, "查询成功", maintainOrder);

    }

    @Override
    public Result updateMaintainOrder(EqMaintainOrder eqMaintainOrder) {
        if(eqMaintainOrder.getMaintainStatus().equals("15")){
            eqMaintainOrder.setMaintainStatus("10");
        }
        boolean save = this.updateById(eqMaintainOrder);
        if (save) {
            //person
            //先删除 再添加或修改
            LambdaQueryWrapper<EqMaintainPerson> delPersonWrapper = new LambdaQueryWrapper<>();
            delPersonWrapper.eq(EqMaintainPerson::getMaintainId,eqMaintainOrder.getId());
            eqMaintainPersonMapper.delete(delPersonWrapper);
            List<EqMaintainPerson> eqMaintainPersonList = eqMaintainOrder.getMaintainPersonList();
            boolean b = eqMaintainPersonService.saveBatch(eqMaintainPersonList);

            //Detail
            //先删除 再添加或修改
            LambdaQueryWrapper<EqMaintainDetail> delDetailWrapper = new LambdaQueryWrapper<>();
            delDetailWrapper.eq(EqMaintainDetail::getMaintainId,eqMaintainOrder.getId());
            eqMaintainDetailMapper.delete(delDetailWrapper);
            List<EqMaintainDetail> eqMaintainDetailList = eqMaintainOrder.getMaintainDetailList();
            boolean c = eqMaintainDetailService.saveBatch(eqMaintainDetailList);
            return Result.succ(1, "编辑成功", eqMaintainOrder);

        }else {
            return Result.fail("编辑失败");
        }
    }

    @Override
    public Result verifyMaintainOrder(EqMaintainDto dto) {
        List<EqMaintainOrder> eqMaintainOrderList = dto.getEqMaintainOrderList();
        for(EqMaintainOrder eqMaintainOrder : eqMaintainOrderList){
            eqMaintainOrder.setMaintainStatus(dto.getMaintainStatus());
        }
        boolean b = this.updateBatchById(eqMaintainOrderList);
        if(b){
            return Result.succ(1, "成功", null);
        }else {
            return Result.fail(400,"失败","");
        }
    }

    @Override
    public Result batchDeleteMaintainOrderList(EqMaintainDto dto) {
        List<EqMaintainOrder> eqMaintainOrderList = dto.getEqMaintainOrderList();
        List<String> ids = eqMaintainOrderList.stream().map(EqMaintainOrder::getId).collect(Collectors.toList());
        boolean b = this.removeByIds(ids);
        if(b){
            //person
            LambdaUpdateWrapper<EqMaintainPerson> deleteTableWrapper = new LambdaUpdateWrapper<>();
            deleteTableWrapper.in(EqMaintainPerson::getMaintainId, ids);
            eqMaintainPersonMapper.delete(deleteTableWrapper);
            //Detail
            LambdaUpdateWrapper<EqMaintainDetail> deleteSelectWrapper = new LambdaUpdateWrapper<>();
            deleteSelectWrapper.in(EqMaintainDetail::getMaintainId, ids);
            eqMaintainDetailMapper.delete(deleteSelectWrapper);
            return Result.succ(1, "删除成功", null);
        }else {
            return Result.fail(400,"删除失败","");
        }
    }

    @Autowired
    EqEquiptTypeMapper eqEquiptTypeMapper;
    @Autowired
    EqEquipmentMapper eqEquipmentMapper;
    @Override
    public Result getMaintainTjfxByEqType(EqRepairParam param) {
        //查出所有的设备分类
        LambdaQueryWrapper<EqEquiptType> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(EqEquiptType::getDelFlag, 0);
        List<EqEquiptType> equiptTypeList = eqEquiptTypeMapper.selectList(lambdaQueryWrapper);
        //查出顶端分类
        List<EqEquiptType> parentTypeList = equiptTypeList.stream().filter(a -> ToolsUtils.isEmpty(a.getParentId())).collect(Collectors.toList());
        //查出所有的设备
        MPJLambdaWrapper<EqEquipment> eqMPJLambdaWrapper = new MPJLambdaWrapper<>();
        eqMPJLambdaWrapper.selectAll(EqEquipment.class)
                .eq(EqEquipment::getDelFlag, 0);

        List<EqEquipment> eqEquipmentList = eqEquipmentMapper.selectList(eqMPJLambdaWrapper);
        //查出所有的设备维修工单
        String monthType = param.getMonthType();
        String paramMonth = param.getMonth();

        MPJLambdaWrapper<EqMaintainOrder> reMPJLambdaWrapper = new MPJLambdaWrapper<>();
        reMPJLambdaWrapper.selectAll(EqMaintainOrder.class)
                .eq(EqMaintainOrder::getDelFlag, 0);

        if(ToolsUtils.isNotEmpty(monthType)){
            Date today=null;
            if(monthType.equals("thisMonth")){
                //本月
                YearMonth currentYearMonth = YearMonth.now();
                int year = currentYearMonth.getYear();
                int month = currentYearMonth.getMonthValue();
                today = DateUtil.parse(year+"-"+month, "yyyy-MM");

            }else if(monthType.equals("lastMonth")){
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.MONTH, -1);
                Date lastMonth = calendar.getTime();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
                String formattedDate = dateFormat.format(lastMonth);
                today = DateUtil.parse(formattedDate, "yyyy-MM");

            }
            reMPJLambdaWrapper.ge(EqMaintainOrder::getCreateTime, DateUtil.beginOfMonth(today).toTimestamp())
                    .le(EqMaintainOrder::getCreateTime, DateUtil.endOfMonth(today).toTimestamp());
        }else {
            if(ToolsUtils.isNotEmpty(paramMonth)){
                Date today = DateUtil.parse(paramMonth, "yyyy-MM");
                reMPJLambdaWrapper.ge(EqMaintainOrder::getCreateTime, DateUtil.beginOfMonth(today).toTimestamp())
                        .le(EqMaintainOrder::getCreateTime, DateUtil.endOfMonth(today).toTimestamp());
            }
        }

        List<EqMaintainOrder> eqMaintainOrderList = eqMaintainOrderMapper.selectList(reMPJLambdaWrapper);
        List<MaintainTjfxVo> voList = new ArrayList<>();
        for(EqEquiptType parentType : parentTypeList){
            MaintainTjfxVo vo= new MaintainTjfxVo();
            vo.setEquiptTypeCode(parentType.getEquiptTypeCode());
            vo.setEquiptTypeId(parentType.getId());
            vo.setEquiptTypeName(parentType.getEquiptTypeName());

            List<EqEquiptType> returnList = new ArrayList<>();
            returnList.add(parentType);
            //取出下边所有的分类
            getChild(parentType,equiptTypeList,returnList);
            List<String> equiptTypeCodeList = returnList.stream().map(EqEquiptType::getEquiptTypeCode).collect(Collectors.toList());
            //设备分类下所有的设备
            List<EqEquipment> equipmentList = eqEquipmentList.stream().filter(a -> equiptTypeCodeList.contains(a.getEquiptTypeCode())).collect(Collectors.toList());
            //总台数
            vo.setEquiptCnt(equipmentList.size());
            List<String> equiptCodeList = equipmentList.stream().map(EqEquipment::getEquiptCode).collect(Collectors.toList());
            List<EqMaintainOrder> maintainOrderList = eqMaintainOrderList.stream().filter(a -> equiptCodeList.contains(a.getEquiptCode())).collect(Collectors.toList());
            //维修台数
            vo.setMaintainEqCnt(maintainOrderList.stream().map(EqMaintainOrder::getEquiptId).distinct().collect(Collectors.toList()).size());
            //总维修数
            vo.setMaintainCnt(maintainOrderList.size());
            //已保养数量
            List<EqMaintainOrder> collect = maintainOrderList.stream().filter(a -> a.getMaintainStatus().equals("15")).collect(Collectors.toList());
            vo.setMaintainedCnt(collect.size());
            if(ToolsUtils.isNotEmpty(collect)){
                //维修用时
                vo.setWorkHours(collect.stream().filter(a->ToolsUtils.isNotEmpty(a.getWorkHours())).mapToInt(EqMaintainOrder::getWorkHours).sum());
            }else {
                vo.setWorkHours(0);
            }
            //计划保养数量
            vo.setPlanMaintainCnt(maintainOrderList.stream().filter(a->ToolsUtils.isNotEmpty(a.getPlanId())).collect(Collectors.toList()).size());
            //快速工单数量
            vo.setKsMaintainCnt(maintainOrderList.stream().filter(a->ToolsUtils.isEmpty(a.getPlanId())).collect(Collectors.toList()).size());
            voList.add(vo);

        }

        return Result.succ(voList);
    }

    private void getChild(EqEquiptType m, List<EqEquiptType> folderList,List<EqEquiptType> returnList) {
        List<EqEquiptType> result = new ArrayList();
        for (EqEquiptType to : folderList) {
            if (ToolsUtils.isNotEmpty(to.getParentId())&&to.getParentId().equals(m.getId())) {
                result.add(to);
            }
        }

        for (EqEquiptType ma : result) {
            returnList.add(ma);
            getChild(ma, folderList,returnList);
        }

    }


}
